package com.yu.crm.utils;

import com.yu.crm.domain.request.LogReq;
import com.yu.crm.domain.response.LogRes;
import com.yxzz.common.helper.DataHelpers;
import com.yxzz.common.helper.ResourceConfigHelpers;
import lombok.extern.log4j.Log4j2;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.nio.channels.FileChannel;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

@Log4j2
public class FileUtil {

    //获取所有的文件
    public static List<LogRes> ergodic(String path, LogReq req){
        List<LogRes> logResList = new ArrayList<>();
        if (DataHelpers.isNotEmptyString(req.getSerach())) {
            path = path + File.separator +req.getSerach();
        }
        try{
            File f = new File(path);
            File fa[] = f.listFiles();
            for (int i = 0; i < fa.length; i++) {
                File fs = fa[i];
                if (fs.isDirectory()) {
                    //当前目录为log目录
                    File[] files = fs.listFiles();
                    if (DataHelpers.isNotEmpty(files) && files.length>0) {
                        for (File file:files
                             ) {
                            LogRes logRes = getLogRes(file, fs.getName());
                            if (DataHelpers.isNotEmptyString(req.getDate())) {
                                if (DataHelpers.isNotEmpty(logRes) && req.getDate().equals(logRes.getCreateTime())){
                                    logResList.add(logRes);
                                }
                            }else {
                                logResList.add(logRes);
                            }
                        }
                    }
                }else {
                    //当前目录为log目录下面的应用目录
                    LogRes logRes = getLogRes(fs, req.getSerach());
                    if (DataHelpers.isNotEmptyString(req.getDate())
                            && DataHelpers.isNotEmpty(logRes)
                            && req.getDate().equals(logRes.getCreateTime())) {
                        logResList.add(logRes);
                    }else {
                        logResList.add(logRes);
                    }
                }
            }
        }catch (Exception e){
            log.error("获取文件失败：{}"+e.getMessage());
            e.printStackTrace();
        }
        return logResList;
    }

    /**
     * 获取LogRes
     * @param fs
     * @param search
     * @return
     */
    public static LogRes getLogRes(File fs,String search) {
        LogRes logRes = new LogRes();
        String substring = fs.getName().substring(0, 5);
        String createDate = fs.getName().substring(0, 10);
        if ("today".equals(substring)) {
            logRes.setCreateTime(DateUtil.getDate());
        }else {
            logRes.setCreateTime(createDate);
        }
        logRes.setFileName(fs.getName());
        FileInputStream fis = null;
        FileChannel fc = null;
        try {
            fis = new FileInputStream(fs);
            fc = fis.getChannel();
            logRes.setFileSize(fc.size());
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            if(null!=fc){
                try {
                    fc.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(null!=fis){
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        logRes.setAppName(search);
        return logRes;
    }

    //读取所有的文件
    public static  List<String> readFileUtil(String filePath){
        List<String> logInfoList = new ArrayList<>();
        File file = null;
        try {
            if(filePath!=null){
                file = new File(filePath);
                // FileReader fileReader = null;
                String tempstr=null;
                StringBuffer sb=new StringBuffer();
                try {
                    // fileReader = new FileReader(file);
                    BufferedReader br=new BufferedReader(new InputStreamReader(new FileInputStream(file)));
                    while((tempstr=br.readLine())!=null){
                        // tempstr = new String(tempstr.getBytes("iso-8859-1"),"UTF-8");
                        logInfoList.add(tempstr);
                    }
                } catch (FileNotFoundException e) {
                    log.error("日志文件没有找到");
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }catch (Exception e){
            log.error(e.toString());
            e.printStackTrace();
        }
        return logInfoList;
    }


    public static String uploadPictures(MultipartFile file) {
        DateFormat df1 = new SimpleDateFormat("yyyyMM");

        String uuid = UUID.randomUUID().toString().replace("-", "");
        //获取文件后缀
        String fileName = file.getOriginalFilename();
        String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);

        //目录地址
        String src = ResourceConfigHelpers.getProperty("wechat.gzhImg") + "/" + df1.format(new Date());
        File file1 = new File(src);
        if (!file1.exists()) {
            file1.mkdirs();
        }
        //拼接生成的地址
        src += "/" + uuid + "." + suffix;
        String fileUrl = ResourceConfigHelpers.getProperty("wechat.qyhImg.url") + "/" + df1.format(new Date()) + "/" + uuid + "." + suffix;
        try {
            MultipartFileToFile.multipartFileToFile(file, src);

            return fileUrl;

        } catch (Exception e) {
            e.printStackTrace();

        }

        return null;

    }

    /**
     * 删除超过howDays的文件
     * @param fromDir
     * @param howDays 文件保存期限
     * @return
     */
    public static void moveFileToReady(String fromDir,int howDays ) {
        File srcDir = new File(fromDir);
        if (!srcDir.exists()) {
            return;
        }
        File[] files = srcDir.listFiles(); //获得该文件下所有的文件
        if (files == null || files.length <= 0) {
            return;
        }
        // 删除文件总数
        Date today = new Date();//当前时间
        for (int i = 0; i < files.length; i++) {
//            if (files[i].isFile()) {
                try {
                    File ff = files[i];
                    long time = ff.lastModified();//文件创建时间
                    Calendar cal = Calendar.getInstance();
                    cal.setTimeInMillis(time);
                    Date lastModified = cal.getTime();
                    long days = getDistDates(today, lastModified);
                    // 删除多少天前之前文件
                    if (days >= howDays) {
                        files[i].delete();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
//            }
        }
    }

    /**
     * 两个日期相隔数 秒
     * @param startDate
     * @param endDate
     * @return
     */
    public static long getDistDates(Date startDate, Date endDate) {
        long totalDate = 0;
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(startDate);
        long timestart = calendar.getTimeInMillis();
        calendar.setTime(endDate);
        long timeend = calendar.getTimeInMillis();
        totalDate = Math.abs((timeend - timestart)) / (1000 * 60 * 60 * 24);
        return totalDate;
    }

}
